#include "node.h"

Node::Node(QString name)
{
    this->key = name;
    this->list = new Nodes;
    QTime midnight(0, 0, 0);
    qsrand(midnight.secsTo(QTime::currentTime()));
}

bool Node::addNode(Node* node)
{
    bool ret = false;
    if(this->getKey().compare(node->getKey()) != 0)
    {
        //qDebug() << "Inserto nodo de nombre " << node->getKey() << " en nodo: " << this->getKey();
        this->list->append(node);
        ret = true;
    } else
    {
       // De momento dos palabras seguidas no pueden estar repetidas.
       // this->list->append(this);
    }

    return ret;
}

bool Node::save(QFile *file)
{
    QDataStream ds(file);
    //qDebug() << "Sizeof de " << this->getKey() << " : " << this->getKey().length() * sizeof(QChar);
    //ds << (qint32) this->getKey().length() * sizeof(QChar);
    ds << this->getKey();
    ds << (qint32) this->getCountWords();
    for(qint32 i = 0; i < this->getCountWords(); i++)
    {
        Node* node = this->list->at(i);
        //ds << node->getKey().length();
        ds << node->getKey();
    }

    return true;
}

bool Node::load(QFile *file)
{
    Node* node = 0;
    QString text;
    QDataStream ds(file);
    ds >> text;
    if(text.compare("_Factory") == 0)
    {
        node = this;
        this->key = text;
    } else
    {
        node = this->searchNode(new Node(text));
    }

    qint32 countWords = 0;
    ds >> countWords;
    for(qint32 i = 0; i < countWords; i++)
    {
        ds >> text;
        Node* otherNode = this->searchNode(new Node(text));
        if(otherNode == 0)
        {
            otherNode = new Node(text);
        }
        node->addNode(otherNode);
    }

    return true;
}

void  Node::showNodes()
{
    for (int i = 0; i < this->list->size(); i++)
    {
        Node* nd = this->list->at(i);
        if(nd == 0)
        {
            qDebug() << "------------------------->Error nodo no encontrado";
        } else
        {
            qDebug() << nd->getKey() << " ---> " <<  nd->list->size() << " list size." ;
        }
    }
}

Node* Node::getRandomNode()
{
    Node* node = 0;
    if(this->list->size() > 0)
    {
        int index = qrand() % this->list->size();
        node = this->list->at(index);
    }
    return node;
}

Node* Node::searchNode(Node* node)
{
    Node* nodefind = 0;
    if(node != 0)
    {
        for (int i = 0; i < this->list->size(); i++)
        {
            Node* nd = this->list->at(i);
            if(nd != 0)
            {
                if(nd->getKey().compare(node->getKey()) == 0)
                {
                    nodefind = nd;
                    break;
                }
            }
        }
    }

    return nodefind;
}

Node* Node::getNode(qint32 index)
{
    return this->list->at(index);
}

void Node::test()
{
    qDebug("Test");
    Node* node = searchNode(new Node("o"));
    node->showNodes();
}
